import { route } from 'quasar/wrappers'
import { createMemoryHistory, createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
import { LoadingBar } from 'quasar'
import routes from './routes'
import { getUserInfo, loginRouteName } from '@/common'

/*
 * If not building with SSR mode, you can
 * directly export the Router instantiation;
 *
 * The function below can be async too; either use
 * async/await or return a Promise which resolves
 * with the Router instance.
 */

const createHistory = process.env.SERVER ? createMemoryHistory : process.env.VITE_APP_ROUTE_HISTORY_MODE === 'history' ? createWebHistory : createWebHashHistory
const useLoadingBar = !!process.env.VITE_APP_LOADINGBAR_COLOR

export default route((/* {  store, ssrContext } */) => {
  const router = createRouter({
    scrollBehavior: (to, from, savedPosition) => {
      if (savedPosition) {
        return savedPosition
      }
      return { left: 0, top: 0 }
    },
    routes,

    // Leave this as is and make changes in quasar.conf.js instead!
    // quasar.conf.js -> build -> vueRouterMode
    // quasar.conf.js -> build -> publicPath
    history: createHistory(process.env.VUE_ROUTER_BASE),
  })

  const needToken = process.env.VITE_APP_HEADTOKENKEY
  let checkToken = () => true

  if (needToken) {
    checkToken = (to, from, next) => {
      const userInfo = getUserInfo()
      if (userInfo?.[process.env.VITE_APP_USERTOKENKEY]) {
        if (to.name === loginRouteName) {
          if (from?.name) {
            next({ name: from.name })
          } else {
            next('/')
          }
        } else {
          return true
        }
      } else if (to.name === loginRouteName || to.meta.noNeedToken) {
        return true
      } else {
        next({ path: `/${loginRouteName}`, query: { aimRouteName: to.name } })
      }
      return false
    }
  }

  router.beforeEach((to, from, next) => {
    if (checkToken(to, from, next)) {
      if (useLoadingBar) {
        LoadingBar.start()
      }
      next()
    }
  })

  router.afterEach(() => {
    if (useLoadingBar) {
      LoadingBar.stop()
    }
  })

  return router
})
